package com.freeman.cement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bestvike.linq.Linq;
import com.freeman.cement.entity.ResponseResult;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.mapper.StaffDao;
import com.freeman.cement.entity.Staff;
import com.freeman.cement.service.StaffService;
import com.freeman.cement.util.SysConst;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.sql.Timestamp;
import java.util.Date;

@Service
public class StaffServiceImpl implements StaffService {

    //引用类型的自动注入@Autowired,@Resource
    @Resource
    private StaffDao staffDao;

    @Override
    public Staff UserLoginCheck(String username, String password) {
        Staff staff = staffDao.UserLoginCheck(username, password);
        if (staff != null) {
            //使用mybatis-plus
            Staff _staff = new Staff();
            _staff.setId(staff.getId());
            _staff.setLoginTime(new Timestamp(new Date().getTime()));
            staffDao.updateById(_staff);
            //使用自定义方法
            //staffDao.updateLoginTime(staff.getId(), new Date());
        }
        return staff;
    }

    @Override
    public void UserLogout(int id) {
        staffDao.updateLogoutTime(id, new Timestamp(new Date().getTime()));
    }

    /**
     * 可以用来参考linq的使用
     *
     * @param staff
     * @return
     */
    @Override
    public List<Staff> findStaffs(Staff staff) {
        List<Staff> staffs = new ArrayList<>();
        //通过输入用户编码进行查找
        if (staff.getUserCode() != null && !staff.getUserCode().equals("")) {
            staffs.add(staffDao.selectStaffsByUserCode(staff.getUserCode()));
        } else {
            staffs = staffDao.selectAllStaff();
            //linq使用参照 https://www.cnblogs.com/shadoll/p/14292909.html
            if (staff.getUsername() != null && !staff.getUsername().equals("")) {
                staffs = Linq.of(staffs).where(x -> x.getUsername().equals(staff.getUsername())).toList();
            }
            if (staff.getDeptName() != null && !staff.getDeptName().equals("")) {
                staffs = Linq.of(staffs).where(x -> x.getDeptName().equals(staff.getDeptName())).toList();
            }
            if (staff.getWorksection() != null && !staff.getWorksection().equals("")) {
                staffs = Linq.of(staffs).where(x -> x.getWorksection().equals(staff.getWorksection())).toList();
            }
            if (staff.getStatus() != null && !staff.getStatus().equals("")) {
                staffs = Linq.of(staffs).where(x -> x.getStatus().equals(staff.getStatus())).toList();
            }
            if (staff.getRole() != null && !staff.getRole().equals("")) {
                staffs = Linq.of(staffs).where(x -> x.getRole().equals(staff.getRole())).toList();
            }
        }
        return staffs;
    }

/*    @Override
    public Staff findStaffByUsercode(String user_code) {
        //通过输入用户编码进行查找
        if (StringUtils.isNotBlank(user_code)) {
            return staffDao.selectStaffsByUserCode(user_code);
        }
        return null;
    }*/

    @Override
    public ResponseResult selectStaff(Staff staff, int pageNo, int pageSize) {
        //验证分页范围
        if (pageNo < 1 || pageSize > 1000) {
            throw new AppException(AppExceptionCodeMsg.PAGE_NO_OR_SIZE_WRONG);
        } else {
            //加入PageHelper的方法，进行分页
            //pageNum:第几页，从1开始；
            //pageSize:一页中要多少行数据；
            //count:是否进行count查询，每页显示数量
            PageHelper.startPage(pageNo, pageSize, true);
            List<Staff> staffs = staffDao.selectStaff(staff);
            PageInfo<Staff> list = new PageInfo<Staff>(staffs);
            return ResponseResult.success(list);
        }
    }

    private boolean checkUsername(String username) {
        QueryWrapper<Staff> q1 = new QueryWrapper<>();
        q1.select("username").eq("username", username);
        Long a = staffDao.selectCount(q1);
        if (a > 0) {
            throw new AppException(AppExceptionCodeMsg.NAME_EXIST);
        }
        return true;
    }

    private boolean checkUserCode(String userCode) {
        QueryWrapper<Staff> q2 = new QueryWrapper<>();
        q2.select("user_code").eq("user_code", userCode);
        Long b = staffDao.selectCount(q2);
        if (b > 0) {
            throw new AppException(AppExceptionCodeMsg.CODE_EXIST);
        }
        return true;
    }

    @Override
    public ResponseResult addStaff(Staff staff) {
        //检查登录名是否为空
        if (staff != null && StringUtils.isNotBlank(staff.getUsername())) {
            //检查登录名是否已存在
            checkUsername(staff.getUsername());

            // user_code生成逻辑
            if (StringUtils.isBlank(staff.getUserCode())) {
                // 生成user_code：username+deptId+roleId+worksectionId
                String userCode = staff.getUsername();
                if (staff.getDeptId() != null) {
                    userCode += "_d" + staff.getDeptId();
                }
                if (staff.getRoleId() != null) {
                    userCode += "_r" + staff.getRoleId();
                }
                if (staff.getWorksectionId() != null) {
                    userCode += "_w" + staff.getWorksectionId();
                }
                staff.setUserCode(userCode);
            } else {
                //检查员工编号是否已存在
                checkUserCode(staff.getUserCode());
            }

            //设置初始密码
            staff.setPassword(SysConst.DefaultUserPassword);

            // 处理生日字段
            if (StringUtils.isBlank(staff.getBirthday())) {
                staff.setBirthday(null);  // 如果生日为空字符串，设置为null
            }

            //存入数据库
            int insert = staffDao.insert(staff);
            if (insert > 0) {
                return ResponseResult.success("新增员工成功", staff.getId());
            } else
                throw new AppException(AppExceptionCodeMsg.ADD_STAFF_ERROR);
        } else {
            throw new AppException(AppExceptionCodeMsg.USERNAME_IS_NULL);
        }
    }

    @Override
    public ResponseResult deleteStaff(int id) {
        if (id > 0) {
            Staff staff = staffDao.selectById(id);
            if (staff != null) {
                int cnt = staffDao.deleteById(id);
                if (cnt > 0) {
                    return ResponseResult.success("删除成功", null);
                } else {
                    throw new AppException(AppExceptionCodeMsg.DELETE_STAFF_ERROR);
                }
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

    /**
     * 修改人员信息，改接口不可用于修改密码
     *
     * @param staff
     * @return
     */
    @Override
    public ResponseResult updateStaff(Staff staff) {
        if (staff != null && staff.getId() != null && staff.getId() > 0) {
            Staff old = staffDao.selectById(staff.getId());
            if (old != null) {
                if (staff.getUsername() != null && StringUtils.isNotBlank(staff.getUsername()) && !staff.getUsername().equals(old.getUsername())) {
                    checkUsername(staff.getUsername());
                }
                if (staff.getUserCode() != null && StringUtils.isNotBlank(staff.getUserCode()) && !staff.getUserCode().equals(old.getUserCode())) {
                    checkUserCode(staff.getUserCode());
                }
                //！！！ 该接口不可用于设置密码 ！！！
                staff.setPassword(null);
                staff.setId(old.getId());
                int rslt = staffDao.updateById(staff);
                if (rslt > 0) {
                    return ResponseResult.success("修改成功", null);
                } else {
                    throw new AppException(AppExceptionCodeMsg.UPDATE_STAFF_ERROR);
                }
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }

    }

    /**
     * 用户修改自己的密码，需要用户知道自己的原有密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @Override
    public ResponseResult editPasswordByStaff(int id, String oldPassword, String newPassword) {
        if (id > 0) {
            Staff old = staffDao.selectById(id);
            if (old != null) {
                if (oldPassword.equals(old.getPassword())) {
                    Staff _staff = new Staff();
                    _staff.setId(old.getId());
                    //改啥设置啥
                    _staff.setPassword(newPassword);
                    int rslt = staffDao.updateById(_staff);
                    if (rslt > 0) {
                        return ResponseResult.success("修改成功", null);
                    } else {
                        throw new AppException(AppExceptionCodeMsg.UPDATE_PASSWORD_ERROR);
                    }

                } else {
                    throw new AppException(AppExceptionCodeMsg.PASSWORD_WRONG);
                }

            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

    @Override
    public ResponseResult editPasswordByAdmin(int id, String newPassword) {
        if (id > 0) {
            Staff old = staffDao.selectById(id);
            if (old != null) {
                Staff _staff = new Staff();
                _staff.setId(old.getId());
                //改啥设置啥
                _staff.setPassword(newPassword);
                int rslt = staffDao.updateById(_staff);
                if (rslt > 0) {
                    return ResponseResult.success("修改成功", null);
                } else {
                    throw new AppException(AppExceptionCodeMsg.UPDATE_PASSWORD_ERROR);
                }
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

    @Override
    public ResponseResult selectStaffByKeyword(String keyword, int pageNo, int pageSize) {
        if (pageNo < 1 || pageSize > 1000) {
            throw new AppException(AppExceptionCodeMsg.PAGE_NO_OR_SIZE_WRONG);
        }
        PageHelper.startPage(pageNo, pageSize, true);
        /*QueryWrapper<Staff> qw = new QueryWrapper<>();
        qw.like("realname", keyword).or().like("user_phone", keyword).orderByDesc("id");
        List<Staff> list = staffDao.selectList(qw);*/
        List<Staff> list = staffDao.selectStaffByKeyword(keyword);
        PageInfo<Staff> pageInfo = new PageInfo<Staff>(list);
        return ResponseResult.success(pageInfo);
    }


}
